<template>
  <div class="app-container">
    <div class="filter-area">
      <vue-scroll>
        <el-input placeholder="输入关键字进行过滤" v-model="filterText" style="margin-bottom: 10px;"></el-input>

        <el-tree
          class="filter-tree"
          :data="officeTreeData"
          :props="defaultProps"
          accordion
          node-key="classId"
          @node-click="nodeClick"
          :expand-on-click-node="true"
          :filter-node-method="filterNode"
          ref="officeTree"
        ></el-tree>
      </vue-scroll>
    </div>

    <div style="float: right;width: calc(100% - 210px);">
      <div style="font-size: 24px;padding-bottom: 10px">{{checkedOffice.officeName}}</div>
      <div class="filter-container">
        <div class="filter-block">
          <span>姓名：</span>
          <el-input size="small" v-model="listQuery.realName" @keyup.enter.native="fetchData(true)"></el-input>
        </div>
        <div class="filter-block">
          <span>状态：</span>
          <el-select
            clearable
            size="small"
            v-model="listQuery.status"
            placeholder="请选择"
            filterable
            @change="fetchData(true)"
          >
            <el-option
              v-for="item in faceStatusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </div>
        <div class="filter-btn-area">
          <el-button size="small" type="primary" @click="fetchData(true)">查询</el-button>
          <el-button size="small" type="none" @click="initListQuery">清除</el-button>
        </div>
      </div>

      <el-table :data="tableData" border highlight-current-row style="width: 100%">
        <el-table-column label="头像" align="center">
          <template slot-scope="scope">
            <div
              @click.stop="getCheckId(scope.row)"
              @contextmenu="avatarMouseOver($event,scope.row)"
            >
              <el-upload
                class="avatar-uploader"
                :action="uploadImgUrl"
                :show-file-list="false"
                :on-success="handlePhotoSuccess"
                :before-upload="beforePhotoUpload"
                with-credentials
              >
                <el-tooltip
                  class="item"
                  effect="light"
                  placement="right"
                  v-if="scope.row.facePhoto"
                >
                  <div slot="content">
                    <img
                      v-if="scope.row.facePhoto"
                      :src="scope.row.facePhoto"
                      title="更新头像"
                      class="avatar"
                    />
                  </div>
                  <img
                    v-if="scope.row.facePhoto"
                    :src="scope.row.facePhoto"
                    title="更新头像"
                    class="avatar me-avatar"
                  />
                </el-tooltip>
                <!--<img v-if="userInfoForm.facePhoto" :src="userInfoForm.facePhoto" class="avatar">-->
                <i v-else class="el-icon-plus avatar-uploader-icon" title="上传头像"></i>
              </el-upload>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="姓名" prop="realName" align="center"></el-table-column>
        <!--<el-table-column label="学号" prop="userId" align="center">-->
        <!--</el-table-column>-->

        <el-table-column label="学号" align="center">
          <template slot-scope="scope">-</template>
        </el-table-column>

        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <span
              :style="formatFaceColor(parseInt(scope.row.faceStatus))"
            >{{formatFaceStatus(parseInt(scope.row.faceStatus))}}</span>
          </template>
        </el-table-column>

        <el-table-column label="失败原因" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.failReason ? scope.row.failReason : "-"}}</span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageInfo.pageNum"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.total"
      ></el-pagination>
    </div>
    <el-dialog :visible.sync="previewData.imgDialog" custom-class="preview-img">
      <img width="100%" :src="previewData.imgUrl" alt />
    </el-dialog>
  </div>
</template>

<script>
import { listAllGrade, listAllCalssStudents, updateFacePhoto } from '@/api/api'
import { officeArrayToTreeWithOfficeType } from '@/utils/utils'
import waves from '@/directive/waves'
import vueScroll from '@/components/vuescroll/vue-scroll.vue'
import { mapGetters } from 'vuex'
import resultData from './resultData'
export default {
  directives: {
    waves
  },
  components: {
    vueScroll
  },
  computed: {
    ...mapGetters(['permissions'])
  },
  data() {
    return {
      //文件上传相关
      pictureType: [
        'image/gif',
        'image/jpeg',
        'image/jpg',
        'image/bmp',
        'image/png'
      ],
      uploadImgUrl: process.env.VUE_APP_PMS_API + '/busi/upload/img?code=1',
      tableData: [],
      pageInfo: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      /*** 图片预览相关    ***/
      previewData: {
        imgDialog: false,
        imgUrl: ''
      },
      buttonType: '',
      faceStatusList: [
        { label: '全部', value: null },
        { label: '未上传', value: 0 },
        { label: '成功', value: 1 },
        { label: '校验中', value: 2 },
        { label: '失败', value: 3 }
      ],

      listQuery: {
        username: '',
        realName: '',
        roleId: '',
        status: ''
      },
      userInfoForm: {
        userId: '',
        facePhoto: ''
      },
      schoolId: sessionStorage.getItem('schoolId'),

      defaultProps: {
        children: 'children',
        label: 'officeName'
      },
      officeTreeData: [],
      checkedOffice: {
        // classId: sessionStorage.getItem('schoolId')
      },
      filterText: ''
    }
  },

  methods: {
    /*** 图片上传相关 ***/
    handlePhotoSuccess(res, file) {
      this.userInfoForm.facePhoto = res.result
      this.saveUserInfo(this.userInfoForm.userId, this.userInfoForm.facePhoto)
    },
    beforePhotoUpload(file) {
      const isPicture = this.pictureType.indexOf(file.type) !== -1
      const isLt2M = file.size / 1024 / 1024 < 10

      if (!isPicture) {
        this.$alert('只能上传图片!', '提示', { type: 'warning' })
      }
      if (!isLt2M) {
        this.$alert('上传照片大小不能超过 10MB!', '提示', { type: 'warning' })
      }
      return isPicture && isLt2M
    },
    /*** 图片预览相关    ***/
    initListQuery() {
      this.listQuery = {
        username: '',
        realName: '',
        roleId: '',
        status: ''
      }
      this.fetchData(true)
    },
    filterNode(value, data) {
      if (!value) return true
      return data.officeName.indexOf(value) !== -1
    },
    initPageInfo() {
      this.pageInfo.pageNum = 1
    },
    fetchData(initPageInfo) {
      this.tableData = []
      if (initPageInfo) {
        this.initPageInfo()
      }
      let params = {
        pageNum: this.pageInfo.pageNum,
        pageSize: this.pageInfo.pageSize,
        classId: this.checkedOffice.classId,
        schoolId: sessionStorage.getItem('schoolId'),
        realName: this.listQuery.realName,
        status: this.listQuery.status
      }
      listAllCalssStudents(params).then(res => {
        if (res.code === 200) {
          this.tableData = []
          this.tableData = res.result && res.result.list ? res.result.list : []
          this.pageInfo.total = res.result.total
        } else {
          this.$message.error(res.message)
        }
      })
      // officeUserScopeList(param).then((res) => {
      //   if (res.code === 200) {
      //     this.tableData = res.result && res.result.list ? res.result.list : [];
      //     this.pageInfo.total = res.result.total;
      //   } else {
      //     this.$message.error(res.message);
      //   }
      // })
    },

    handleSizeChange(val) {
      this.pageInfo.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.pageInfo.pageNum = val
      this.fetchData()
    },
    getSchoolList() {
      listAllGrade({ schoolId: sessionStorage.getItem('schoolId') }).then(
        res => {
          if (res.code == 200) {
            if (res.result && res.result.length && res.result.length > 0) {
              this.checkedOffice = res.result[0].children[0] || ''
              this.officeTreeData = res.result
              this.fetchData()
            }
          } else {
            this.officeTreeData = []
          }
        }
      )
      // officeAccessList({
      //   schoolId : this.schoolId
      // }).then((res) => {
      //   if (res.code === 200) {
      //     if (res.result && res.result.length && res.result.length > 0) {
      //       res.result.forEach((rTmp) => {
      //         if (!rTmp.access) {
      //           rTmp.officeName += " (无权限)";
      //         }
      //       })
      //     }
      //     this.officeTreeData = officeArrayToTreeWithOfficeType(res.message, res.result);
      //     console.log(' this.officeTreeData')
      //     console.log(this.officeTreeData);
      //
      //     this.officeTreeData = address
      //
      //     this.checkedOffice = this.getOfficeFromTreeData(this.officeTreeData, this.checkedOffice.id);
      //     console.log('this.checkedOffice')
      //     console.log(this.checkedOffice)
      //     this.officeTreeData = address.result
      //   } else {
      //     this.$message.error(res.message);
      //   }
      // })
    },
    nodeClick(item) {
      this.tableData = []
      this.checkedOffice = item.classId ? item : item.children[0] || ''
      if (!this.checkedOffice.classId) {
        this.pageInfo = {
          pageNum: 1,
          pageSize: 10,
          total: 0
        }
        this.tableData = []
        return false
      }
      this.fetchData(true)
      // this.officeId = item.id;
    },
    formatFaceColor(code) {
      if (code == 1) {
        return 'color: #02b2b5'
      } else if (code == 2) {
        return 'color: #f67d00'
      } else if (code == 3) {
        return 'color: #FF0000'
      } else {
      }
      return 'color: #333333'
    },
    formatFaceStatus(code) {
      for (let item of this.faceStatusList) {
        if (item.value == code) {
          return item.label
        }
      }
      return null
    },
    formatResultMenu(code) {
      switch (code) {
        case 0:
          return (this.buttonType = 'info')
        case 1:
          return (this.buttonType = 'success')
        case 2:
          return (this.buttonType = 'warning')
        case 3:
          return (this.buttonType = 'danger')
        default:
          return (this.buttonType = 'info')
      }
    },
    //图片上传成功后保存用户信息
    saveUserInfo(userId, facePhoto) {
      let params = {
        schoolId: sessionStorage.getItem('schoolId'),
        classId: this.checkedOffice.classId,
        userId,
        facePhoto
      }
      updateFacePhoto(params).then(res => {
        if (res.code == 200) {
          this.fetchData(false)
        }
      })
    },
    getCheckId(data) {
      this.userInfoForm.userId = data.userId
    }
  },
  created() {
    this.getSchoolList()
  },
  watch: {
    filterText(val) {
      this.$refs.officeTree.filter(val)
    }
  }
}
</script>
<style scoped lang="scss">
.me-avatar {
  width: 75px;
  height: 100px;
}
.avatar-uploader-icon {
  width: 75px;
  height: 100px;
  line-height: 100px;
}
.avatar-uploader-icon {
  font-size: 40px;
}
.filter-area {
  height: 800px;
  width: 200px;
  float: left;
  overflow-y: auto;
  &::after {
    content: '';
    display: block;
    clear: both;
  }
}
</style>
